package com.liao.springclouduser.controller.config.dataSourceConfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @autuor sufei
 * @date 2018/11/21 16:37
 */
@Configuration
@MapperScan(basePackages = {"com.liao.springclouduser.dao.read"}, sqlSessionFactoryRef = "readSqlSessionFactory")
public class MybatisReadDBConfig {


    @Autowired
    @Qualifier("readDataSource")
    private DataSource dataSource;

    @Bean
    public SqlSessionTemplate readSqlSession() throws Exception {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(readSqlSessionFactory());
        return sqlSessionTemplate;
    }

    @Bean
    public SqlSessionFactory readSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resource = resolver.getResources("classpath:mapper/*.xml");
        sqlSessionFactoryBean.setMapperLocations(resource);

        return sqlSessionFactoryBean.getObject();
    }
}
